package net.huashitong.oversee.web;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.node.filter.NodeNewschedulesFilter;
import net.huashitong.oversee.databean.DepartRank;
import net.huashitong.oversee.entity.GradePoint;
import net.huashitong.oversee.entity.ScoreSummary;
import net.huashitong.oversee.entity.SupervisionTask;
import net.huashitong.oversee.filter.CoordinateFilter;
import net.huashitong.oversee.filter.GradePointFilter;
import net.huashitong.oversee.filter.ScoreSummaryFilter;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.service.CoordinateService;
import net.huashitong.oversee.service.GradePointService;
import net.huashitong.oversee.service.ScoreSummaryService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.filter.BnpUserFilter;
import net.huashitong.user.service.BnpUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.*;

import static net.huashitong.utils.UtilsTools.getCurrentDateTime1;

@Controller
@RequestMapping("/scoresummary")
public class ScoreSummaryCtrl extends JsonBaseController {

    @Override
    protected String getView(String s) {
        return "/modules/scoresummary/" + s;
    }

    @Autowired
    private ScoreSummaryService service;
    @Autowired
    private SupervisionTaskService supervisionTaskService;
    @Autowired
    private GradePointService gradePointService;
    @Autowired
    private NewProjectsService newProjectsService;
    @Autowired
    private BnpUserService bnpUserService;


    @RequestMapping(method = RequestMethod.GET)
    public String initPage(HttpServletRequest request, Model model) {
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        //待办任务个数
        int nodeCount = (int) WebUtils.getSessionAttribute(request, "nodeCount");
        model.addAttribute("nodeCount", nodeCount);
        int myTaskNum = (int) WebUtils.getSessionAttribute(request, "myTaskNum");
        int quetionNum = (int) WebUtils.getSessionAttribute(request, "quetionNum");
        model.addAttribute("myTaskNum", myTaskNum);
        model.addAttribute("quetionNum", quetionNum);

        int myTackTaskNum = (int) WebUtils.getSessionAttribute(request, "myTackTaskNum");
        model.addAttribute("myTackTaskNum", myTackTaskNum);

        model.addAttribute("leftType", "绩效考核");
        return getView("query");
    }


    //初始化数据
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid query(@ModelAttribute ScoreSummaryFilter filter) {

        if (filter.isDepartRank()) {
            if (StringUtils.isNotBlank(filter.getPaging().getSortVal())) {
                filter.getPaging().setSortVal("");
            }
            List<DepartRank> list = service.queryDepartRank(filter);
            int num = (filter.getPaging().getCurrentPage() - 1) * 10 + 1;
            for (DepartRank d : list) {
                double x = (double) Math.round(d.getScore() * 100) / 100;
                d.setScore(x);
                d.setRank(num + "");
                d.setCheckDept("——");
                num++;
            }
            return coverJqGrid(filter, list);
        }
        List<ScoreSummary> list = service.queryByFilter(filter);
        if (StringUtils.isBlank(filter.getBranchType())) {
            return coverJqGrid(filter, list);
        } else {
            for (ScoreSummary summary : list) {
                summary.setRank(summary.getTypeRank());
            }
            return coverJqGrid(filter, list);
        }
    }

    @RequestMapping("/filter")
    public String filter(@ModelAttribute BnpUserFilter filter, Model model) {
        //所有部门
        return getView("filter");
    }

    @RequestMapping("/formHead")
    public String showHead(@ModelAttribute NodeNewschedulesFilter filter, Model model) {
        return getView("formHead");
    }

    /**
     * 显示绩效详情
     *
     * @param model
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/showGradePointDetail/{id}", method = RequestMethod.GET)
    public String showGradePointDetail(Model model, HttpServletRequest request, @PathVariable String id) {
        //查询所有失效的任务
        List<String> invalidTasks = new ArrayList<>();
        SupervisionTaskFilter taskFilter = new SupervisionTaskFilter();
        taskFilter.setValid("0");
        List<SupervisionTask> tasks = supervisionTaskService.getTaskListsNoPage(taskFilter);
        for (SupervisionTask t : tasks) {
            invalidTasks.add(t.getSysId());
        }
        ScoreSummary scoreSummary = service.getById(id);
        String checkObjectId = scoreSummary.getUserId();
        GradePointFilter filter = new GradePointFilter();
        filter.setCheckObjectId(checkObjectId);
        List<GradePoint> list = gradePointService.queryGradePoint(filter);
        for (GradePoint g : list) {
            if (invalidTasks.contains(g.getTaskId())) {
                g.setInvalid("1");
            }
        }
        model.addAttribute("list", list);
        return getView("gradePointDetail");
    }


    @ResponseBody
    @RequestMapping(value = "/updateLeaderScoreSummary", method = RequestMethod.GET)
    public Map<String, Object> updateLeaderScoreSummary() {
        return null;
//        //查询所有项目
//        List<NewProjects> allProjects = newProjectsService.query();
//        //将分管领导的项目归纳成一个list
//        Map<String, List<NewProjects>> leaderProjectMap = new HashMap<>();
//        for (NewProjects project : allProjects) {
//            if (!leaderProjectMap.containsKey(project.getResUser() + "-" + project.getResPhone())) {
//                List<NewProjects> list = new ArrayList<>();
//                list.add(project);
//                leaderProjectMap.put(project.getResUser() + "-" + project.getResPhone(), list);
//            } else {
//                List<NewProjects> list = leaderProjectMap.get(project.getResUser() + "-" + project.getResPhone());
//                list.add(project);
//                leaderProjectMap.put(project.getResUser() + "-" + project.getResPhone(), list);
//            }
//        }
//        //查询所有领导
//        BnpUserFilter userFilter = new BnpUserFilter();
//        userFilter.setBranchType("6");
//        List<BnpUser> leaders = bnpUserService.queryByFilter(userFilter);
//
//        Map<String, BnpUser> leadersMap = new HashMap<>();
//        for (BnpUser leader : leaders) {
//            if (!leadersMap.containsKey(leader.getSysId())) {
//                leadersMap.put(leader.getSysId(), leader);
//            }
//        }
//
//        //绩效得分（领导Id，总的绩效得分）
//        Map<String, Double> userScoreMap = new HashMap<>();
//        //绩效考核次数（领导Id，总的绩效个数）
//        Map<String, Integer> userCountMap = new HashMap<>();
//        for (BnpUser leader : leaders) {
//            String leaderKey = leader.getName() + "-" + leader.getPhone();
//            for (Map.Entry<String, List<NewProjects>> entry : leaderProjectMap.entrySet()) {
//                //Map.entry<Integer,String> 映射项（键-值对）  有几个方法：用上面的名字entry
//                //entry.getKey() ;entry.getValue(); entry.setValue();
//                //map.entrySet()  返回此映射中包含的映射关系的 Set视图。
//                //System.out.println("key= " + entry.getKey() + " and value= "
//                //      + entry.getValue());
//
//                String key = entry.getKey();
//                if (key.equals(leaderKey)) {
//                    String leaderSysId = leader.getSysId();
//
//                    List<GradePoint> gradePoints = new ArrayList<>();
//                    //获取该领导的相关所有绩效得分
//                    List<NewProjects> projects = entry.getValue();
//                    for (NewProjects project : projects) {
//                        List<GradePoint> gp = gradePointService.queryByProjectId(project.getSysId());
//                        gradePoints.addAll(gp);
//                    }
//
//                    Double allScore = 0.0;
//                    for (GradePoint g : gradePoints) {
//                        Double score = Double.parseDouble(StringUtils.isBlank(g.getSoucre()) ? "0.0" : g.getSoucre());
//                        allScore = allScore + score;
//                    }
//                    if (allScore != 0.0) {
//                        userScoreMap.put(leaderSysId, allScore);
//                        userCountMap.put(leaderSysId, gradePoints.size());
//                    } else {
//                        userScoreMap.put(leaderSysId, 0.0);
//                        userCountMap.put(leaderSysId, 0);
//                    }
//                }
//            }
//        }
//
//        List<ScoreSummary> scoreSummariesResult = new ArrayList<>();
//        for (Map.Entry<String, Double> entry : userScoreMap.entrySet()) {
//            ScoreSummary summary = new ScoreSummary();
//
//            String userId = entry.getKey();
//            Double allScore = entry.getValue();
//            Double resScore = 0.0;
//            if (ObjectUtils.isNotBlank(leadersMap.get(userId))) {
//                if (userCountMap.get(userId) != 0) {
//                    resScore = allScore / (userCountMap.get(userId)) +
//                            allScore / 10;
//                } else {
//                    resScore = 0.0;
//                }
//                summary.setCheckDept(leadersMap.get(userId).getBranch());
//                summary.setCheckObject(leadersMap.get(userId).getName());
//                summary.setScore(String.format("%.2f", resScore) + "");
//                summary.setUserId(leadersMap.get(userId).getSysId());
//                summary.setSummaryDate(getCurrentDateTime1());
//                summary.setBranchType(leadersMap.get(userId).getBranchType());
//            }
//            scoreSummariesResult.add(summary);
//        }
//
//        Map<String, Object> resMap = new HashMap<>();
//        resMap.put("result", scoreSummariesResult);
//        return resMap;
    }

    /**
     * 获取分管领导得分
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryLeaderScoreSummary", method = RequestMethod.POST)
    public Message queryLeaderScoreSummary(@RequestBody ScoreSummaryFilter filter) {
        String userPhone = filter.getUserPhone();
        String checkObject = "";
        switch (userPhone){
            case "13005912001": checkObject = "许以章"; break;
            case "13005912002": checkObject = "姚伟"; break;
            case "13005912003": checkObject = "柯永华"; break;
            case "13005912004": checkObject = "王礼灯"; break;
            case "13005912005": checkObject = "吴钢"; break;
            case "13005912006": checkObject = "郑建双"; break;
            case "13005912007": checkObject = "曹方敏"; break;
            case "13005912008": checkObject = "李卫榕"; break;
            case "13005912009": checkObject = "陈榕"; break;
            case "13005912010": checkObject = "张庆宗"; break;
            case "13005912011": checkObject = "黄身瑜"; break;
            case "13005912012": checkObject = "罗智林"; break;
            case "13005912013": checkObject = "俞华"; break;
            case "13005912014": checkObject = "魏秀惠"; break;
            case "13005912015": checkObject = "侯一晞"; break;
            case "13005911002": checkObject = "唐磊"; break;
            case "13005912017": checkObject = "余斌"; break;
            case "13005912018": checkObject = "姜应明"; break;
            case "13005912019": checkObject = "邱小文"; break;
            case "13005912020": checkObject = "丁虹"; break;
            case "13005912021": checkObject = "叶俊忠"; break;
            case "13005912022": checkObject = "张文"; break;
            case "13005912023": checkObject = "李志专"; break;
            case "13005912024": checkObject = "江惠文"; break;
            case "13005912025": checkObject = "张培奋"; break;
            case "13005912026": checkObject = "史瑜"; break;
            case "13005912027": checkObject = "王宁"; break;
            case "13005912028": checkObject = "林孝仕"; break;
            case "13005912029": checkObject = "上官浩龙"; break;
            default: break;
        }
        filter.setCheckObject(checkObject);
        filter.setBranchType("6");
        List<ScoreSummary> list = service.queryByFilterNoPage(filter);
        return coverMessage("200", "获取分管领导得分成功", list);
    }
}
